import 'package:fancy_bottom_navigation/fancy_bottom_navigation.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:peach/config/_.dart';
import 'package:peach/utils/_.dart';

import 'package:peach/views/Home/Home.dart';
import 'package:peach/views/Mechanism/Mechanism.dart';
import 'package:peach/views/Model/Model.dart';
import 'package:peach/views/Me/Me.dart';

/*
 * App的页面框架，底部tabs切换在这实现
 */
class App extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _App();
}

class _App extends State<App> with AutomaticKeepAliveClientMixin {
  // 显示第几个页面的下标
  int currentIndex = 0;
  // fancy_bottom_navigation 需要的唯一key
  GlobalKey bottomNavigationKey = GlobalKey();
  // 存储从 bottomNavigationKey 中获取当前底部导航条的组件
  FancyBottomNavigationState fState;
  List<Widget> tabBodies = [ Home(), Mechanism(), Model(), Me() ];
  
  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();

    CheckUpdate().check(context);
    Config.tabController = PageController(initialPage: currentIndex);
  }

  @override
  void dispose() {
    Config.tabController.dispose();
    super.dispose();
  }

  /// 中间内容的组件
  Widget BodyWidget () {
    return PageView(
      controller: Config.tabController,
      children: tabBodies,
      // 整个页面滑动的时候，联动切换底部导航
      onPageChanged: (int index) {
        setState(() {
          currentIndex = index;
          fState = bottomNavigationKey.currentState;
          fState.setPage(currentIndex);
        });
      },
    );
  }

  /// 底部导航
  Widget BottomNavigationWidget() {
    return FancyBottomNavigation(
      key: bottomNavigationKey,
      initialSelection: 0,
      textColor: ColorConfig.ThemeColor,
      inactiveIconColor: ColorConfig.ThemeColor,
      activeIconColor: ColorConfig.WhiteBackColor,
      circleColor: ColorConfig.ThemeColor,
      onTabChangedListener: (position) {
        setState(() {
          currentIndex = position;
          /// 带动画的去切换
          Config.tabController.jumpToPage(currentIndex);
        });
      },
      tabs: [
        TabData(iconData: IconFont.HomeIcon().icon, title: "首页"),
        TabData(iconData: IconFont.MechanismIcon().icon, title: "机构"),
        TabData(iconData: IconFont.ModelIcon().icon, title: "模特"),
        TabData(iconData: IconFont.MeIcon().icon, title: "我的")
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      extendBodyBehindAppBar: false,
      body: BodyWidget(),
      bottomNavigationBar: BottomNavigationWidget(),
    );
  }
}
